package com.hrpc.serialize.impl;

import com.caucho.hessian.io.Hessian2Input;
import com.caucho.hessian.io.Hessian2Output;
import com.hrpc.exceptions.SerializeException;
import com.hrpc.serialize.Serialize;

import java.io.*;

public class HessianSerializeImpl implements Serialize {
    @Override
    public byte[] serialize(Object object) {
        if (object == null){
            return null;
        }
        try(//将流的定义写在这里会自动关闭，不需要再写final了
                ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream()
        ) {
            Hessian2Output hessian2Output = new Hessian2Output(byteArrayOutputStream);
            hessian2Output.writeObject(object);
            hessian2Output.flush();
            return byteArrayOutputStream.toByteArray();
        }catch (IOException e){
            throw new SerializeException("HESSIAN序列化时出错了！！！");
        }
    }

    @Override
    public <T> T deSerialize(byte[] bytes, Class<T> clazz) {
        if (bytes == null ||clazz == null){
            return null;
        }
        try(//将流的定义写在这里会自动关闭，不需要再写final了
            ByteArrayInputStream byteArrayinputStream=new ByteArrayInputStream(bytes);
        ) {
            Hessian2Input hessian2Input = new Hessian2Input(byteArrayinputStream);
            Object object = hessian2Input.readObject();
            return (T) object;
        }catch (IOException e){
            throw new SerializeException("JDK反序列化时出错了！！！");
        }
    }
}
